package com.justech.tcp.server;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName
 * @Author: xiaofeng.yang
 * @Date: Create in 9:43 2019/12/3
 * @Description : TODO
 * @Version: 1.0
 */
public class Sender {
    private static  final Logger logger= LoggerFactory.getLogger(Sender.class);
    private ConsumerConnectionFactory consumerConnectionFactory;
    private String requestRouter;
    private Channel requestChannel;
    private static Sender sender;

    public static Sender getInstance() throws IOException, TimeoutException {
        if (null == sender) {
            synchronized (Sender.class) {
                if (null == sender) {
                    sender = new Sender();
                }
            }
        }
        return sender;
    }

    private Sender() throws IOException, TimeoutException {
        this.requestRouter = System.getProperty("request-router", "message");
        consumerConnectionFactory = ConsumerConnectionFactory.getInstance();
        Connection connection = consumerConnectionFactory.getConnection();
        this.requestChannel = connection.createChannel();
        this.requestChannel.queueDeclare(this.requestRouter, true, false, false, null);
        logger.info("created sender channel:"+this.requestRouter);
    }

    public void send(String message) throws IOException {
        this.requestChannel.basicPublish("", this.requestRouter, null, message.getBytes());
    }

}
